<?php



/**
 * Класс работы с базой данных
 */
 
 $indent = mysql_connect(SERVER_DB, USER_DB, PASS_DB)or die (mysql_error());
 mysql_query("set names utf8");
 mysql_select_db(DB, $indent) or die (mysql_error());  
  
class DBConnect 
{
	/**
	 * 
	 */ 	
	var $error = "";
    var $log;
    static $errorLogFile = "logs/sqlerrors.log" ;   
    static $queryes = array();
    static $time = 0;
    static $all = array();
    
    static $memcach = false;
    static $useMemCache = true;
    static $memCacheHost = '127.0.0.1';
    static $memCachePort = 11211;
    static $memCacheTime = 900;
    static $mailAdmin;# = 'orlac@rambler.ru';
    
	function __construct( $host = '', $username = '', $passwd = '', $dbname = '')
	{
		/*if(!$host) $host = SERVER_DB;
        if(!$username) $username = USER_DB;
        if(!$passwd) $passwd = PASS_DB;
        if(!$dbname) $dbname = DB;        
        
        $indent = mysql_connect($host, $username, $passwd)or die (mysql_error());
        DBConnect::query("set names utf8");
        mysql_select_db($dbname, $indent) or die (mysql_error()); 
        */       				
	}
    
    static function getCach($keyCach = ''){
        if(empty($keyCach) ) return false;        
        if( !self::startmemcach() ) return false;                                
        return self::$memcach->get($keyCach);
        return true;        
    }
    
    static function setCach($keyCach, $data){
        if(empty($keyCach) ) return false;        
        if( !self::startmemcach() ) return false;
        self::$memcach->set($keyCach, $data, MEMCACHE_COMPRESSED, time() + self::$memCacheTime );    ;
        return true;
    }
    
    
    static public function query($sql, $keyCach = ''){
        
        $data = self::getCach($keyCach);
        
        if( $data == 1  ){
            $dataArr = DBConnect::getCach($keyCach.":data");
            if( $dataArr == 1){
                self::logStart( "Load cach of '".$keyCach."'"  );
                self::logEnd(); 
                return true;             
            }                        
        }
        self::logStart( $sql );
                
        
        if(!$result = mysql_query($sql)){
            $errorlog = new log(CORE_PATH.self::$errorLogFile);            
            $errorlog->start("". $sql."\n".mysql_error());           
            if(self::$mailAdmin){
                @mail(self::$mailAdmin, 'SQL Error', $sql."  \n".mysql_error(), 'From: '.__FILE__);    
            }            
            return false;
        }        
        self::logEnd();
        //self::$memcach->delete($keyCach);
        self::setCach($keyCach, 1);
        return $result;
    }
    
    
    static public function getAll($result, $keyCach = ''){
        self::$all = array();        
        $i = 0;
        while($_arr = self::getOne($result, $keyCach)){
            self::$all[] = $_arr;
            $i++;
                
        }
        return $i;
    }
    
    static public function logStart($query){
        self::$time = microtime();
        self::$queryes[] = $query."\n";                    
    }
    
    static public function logEnd(){
        self::$queryes[count(self::$queryes) - 1 ] .= (microtime() - self::$time)."\n\n";
    }
    
    
    static $counter = array();
    static public function getOne($result, $keyCach = ''){
        $result;
        $data = self::getCach($keyCach);        
        if( $data == 1 ){            
            $dataArr = self::getCach($keyCach.":data");                     
            if( $dataArr != 1  ) {
                $i = 0;
                while($_arr = mysql_fetch_assoc($result)){
                    self::setCach($keyCach.":data:".$i, $_arr);    
                    $i++;
                }
                self::setCach($keyCach.":data", 1);
            }
            
            if(!isset(self::$counter[$keyCach])){
                self::$counter[$keyCach] = -1;
            }
            self::$counter[$keyCach]++;            
            $d = self::getCach($keyCach.":data:".self::$counter[$keyCach]);
            if( !$d ){
                unset(self::$counter[$keyCach]);
            }
            return $d;                         
        }else{
            return mysql_fetch_assoc($result);    
        }
    }
    
    
    static function startmemcach(){
    	if( !self::$useMemCache) return false;
    	if(!self::$memcach){
        	self::$memcach = @new Memcache();
        	if( !self::$memcach ) return false;
        	if( !self::$memcach->connect(self::$memCacheHost, self::$memCachePort) ){
        		$errorlog = new log(CORE_PATH.self::$errorLogFile);            
            	$errorlog->start("memcashed Could not connect\n");
            	return false;    
			}                            	
        }
        return true;               
    }
    
    
    static function count($result, $keyCach = '' ){
        #return mysql_num_rows($result);
        $r = self::getAll($result, $keyCach);
        return $r;
    }
    
    static function mysqlCount($result){
        return mysql_num_rows($result);
    }
    
    // текущая дата в формате mysql
    static function mysqlDate( $unixtime = '' )
    {
        if( empty( $unixtime ) ) $unixtime = time();  
        return date( 'Y-m-d H:i:s', $unixtime );
    }
    
    static function mysql_close(){
        mysql_close();
    }
    
    static public function checkData($data){
        if(is_array($data)){
            foreach($data as $key => $val){
                $data[$key] = self::checkData($val);
            }
        }else{
            $data = addslashes($data);
        }
        return $data;
    }
    
}

?>